package component.fy.com.common_module.base;

import android.app.Activity;
import android.app.AppOpsManager;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import cn.sharesdk.onekeyshare.OnekeyShare;
import component.fy.com.common_module.R;
import component.fy.com.common_module.bean.CheckAppVersionBean;
import component.fy.com.common_module.constant.AppConstant;
import component.fy.com.common_module.inter.PermissionListener;
import component.fy.com.common_module.retrofit.ResultCallback;
import component.fy.com.common_module.retrofit.RetrofitManager;
import component.fy.com.common_module.services.UpdateService;
import component.fy.com.common_module.utils.AndroidBug5497Workaround;
import component.fy.com.common_module.utils.LogUtil;
import component.fy.com.common_module.utils.MyUtil;
import component.fy.com.common_module.utils.StatusBarUtil;
import component.fy.com.common_module.utils.ToastUtil;
import component.fy.com.common_module.utils.WeiboDialogUtils;


/**
 * Created by Administrator on 2017/5/11 0011.
 */
public abstract class BaseActivity extends AppCompatActivity {
    private static final String TAG = "BaseActivity";

    //获取布局文件ID
    protected abstract int getLayoutId();

    //布局加载
    protected abstract void initView();

    //监听事件
    protected abstract void initEvents();

    //数据
    protected abstract void initData();

    /**
     * 权限监听接口
     */
    private static PermissionListener perListener;
    protected BaseActivity mActivity;

    private Dialog loadingDialog;//加载数据框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        setContentView(getLayoutId());
        /*if (AndroidWorkaround.checkDeviceHasNavigationBar(this)) {
            AndroidWorkaround.assistActivity(findViewById(android.R.id.content));
        }*/
        AndroidBug5497Workaround.assistActivity(this);//解决键盘冲突的方法
        ButterKnife.bind(this);
//        setStatusBar();//设置状态栏颜色
        initView();
        initEvents();
        initData();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            isNotificationCanUse();//判断消息通知是否打开
        }
    }

    private ImageView imgBack, imgRight;
    private TextView tvTitle;
    private RelativeLayout layoutToolBar, rightLayout;
    private TextView rightLayoutTv;
    private ImageView rightLayoutImg;

    /**
     * 设置ToolBar背景色
     *
     * @param resId
     */
    protected void setToolBarBackground(int resId) {
        layoutToolBar = (RelativeLayout) findViewById(R.id.common_toolbar_layout);
        layoutToolBar.setBackgroundResource(resId);
    }

    /**
     * 获取ToolBar返回键
     *
     * @return
     */
    protected ImageView getToolBarBack() {
        imgBack = (ImageView) findViewById(R.id.common_toolbar_back);
        imgBack.setVisibility(View.VISIBLE);
        return imgBack;
    }

    /**
     * 设置ToolBar返回键
     *
     * @return
     */
    protected ImageView setToolBarBack(int resId) {
        imgBack = (ImageView) findViewById(R.id.common_toolbar_back);
        imgBack.setVisibility(View.VISIBLE);
        imgBack.setImageResource(resId);
        return imgBack;
    }

    /**
     * 设置ToolBar标题
     *
     * @param title
     */
    protected void setToolBarTitle(String title) {
        tvTitle = (TextView) findViewById(R.id.common_toolbar_title);
        tvTitle.setText(title);
    }

    /**
     * 设置Tool标题和颜色
     *
     * @param title
     * @param textColor
     */
    protected void setToolBarTitle(String title, int textColor) {
        tvTitle = (TextView) findViewById(R.id.common_toolbar_title);
        tvTitle.setText(title);
        tvTitle.setTextColor(this.getResources().getColor(textColor));
    }

    /**
     * 设置ToolBar标题及标题颜色、字体大小
     *
     * @param title
     */
    protected void setToolBarTitle(String title, int color, int size) {
        tvTitle = (TextView) findViewById(R.id.common_toolbar_title);
        tvTitle.setText(title);
        tvTitle.setTextColor(mActivity.getResources().getColor(color));
        tvTitle.setTextSize(size);
    }

    /**
     * 设置ToolBar右边图片
     *
     * @param resId
     * @return
     */
    protected ImageView setToolBarRightImg(int resId) {
        imgRight = (ImageView) findViewById(R.id.common_toolbar_right_img);
        imgRight.setVisibility(View.VISIBLE);
        if (resId != 0) {
            imgRight.setImageResource(resId);
        }
        return imgRight;
    }

    /**
     * 获取ToolBar右边图片
     *
     * @return
     */
    protected ImageView getToolBarRightImg() {
        imgRight = (ImageView) findViewById(R.id.common_toolbar_right_img);
        imgRight.setVisibility(View.VISIBLE);
        return imgRight;
    }

    /**
     * 设置并显示右边布局
     *
     * @param tvStr
     * @return
     */
    protected RelativeLayout setToolBarRightLayout(String tvStr) {
        rightLayout = (RelativeLayout) findViewById(R.id.common_toolbar_right_layout);
        rightLayoutTv = (TextView) findViewById(R.id.common_toolbar_right_layout_tv);
        rightLayoutImg = (ImageView) findViewById(R.id.common_toolbar_right_layout_img);
        rightLayout.setVisibility(View.VISIBLE);
        rightLayoutTv.setText(tvStr);
        rightLayoutImg.setSelected(false);
        return rightLayout;
    }

    /**
     * 改变右边布局箭头状态
     */
    protected ImageView getToolBarRightLayoutImg() {
        return rightLayoutImg;
    }

    /**
     * 获取跳转界面时传递的数据
     *
     * @return
     */
    protected Bundle getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            return bundle;
        }
        return null;
    }

    /**
     * 修改状态栏
     */
    protected void setStatusBar(int colorId) {
        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(colorId));
    }

    /**
     * 请求权限
     *
     * @param permissions
     * @param listener
     */
    public void requestRunPermission(String[] permissions, PermissionListener listener) {
        Activity topActivity = BaseCommonApp.getBaseApp().getActivityManager().currentVisibleActivity();
        if (topActivity == null) {
            return;
        }
        perListener = listener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(topActivity, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            //未获取
            ActivityCompat.requestPermissions(topActivity, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            //获取了
            perListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    List<String> deniedList = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedList.add(permission);
                        }
                    }

                    if (deniedList.isEmpty()) {
                        perListener.onGranted();
                    } else {
                        perListener.onDenied(deniedList);
                    }
                }
                break;
        }
    }

    /**
     * activity跳转，不带数据
     *
     * @param from
     * @param to
     */
    protected void goToPage(Context from, Class<? extends Activity> to) {
        Intent i = new Intent();
        i.setClass(from, to);
        from.startActivity(i);
    }

    /**
     * activity跳转，带数据
     *
     * @param from
     * @param to
     * @param data 携带数据
     */
    protected void goToPage(Context from, Class<? extends Activity> to, Bundle data) {
        Intent i = new Intent();
        i.setClass(from, to);
        if (data != null) {
            i.putExtras(data);
        }
        from.startActivity(i);
    }

    /**
     * activity带结果跳转
     *
     * @param from
     * @param to
     * @param requestCode
     */
    protected void goToPageForResult(Context from, Class<? extends Activity> to, int requestCode) {
        Intent i = new Intent(from, to);
        startActivityForResult(i, requestCode);
    }

    /**
     * activity带结果跳转
     *
     * @param from
     * @param to
     * @param data
     * @param requestCode
     */
    protected void goToPageForResult(Context from, Class<? extends Activity> to, Bundle data, int requestCode) {
        Intent i = new Intent(from, to);
        if (data != null) {
            i.putExtras(data);
        }
        startActivityForResult(i, requestCode);
    }

    /**
     * 关闭软键盘
     */
    protected void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 动态隐藏软键盘
     *
     * @param activity activity
     */
    protected void hideSoftInput(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view == null) {
            view = new View(activity);
        }
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 复制内容到系统剪贴板
     *
     * @param context
     * @param content
     */
    protected void copyToClipboard(Context context, String content) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("copy", content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        ToastUtil.showToast("复制成功");
    }

    /**
     * 显示加载框，带参数
     */
    protected void showLoading(String hint) {
        if (TextUtils.isEmpty(hint)) {
            loadingDialog = WeiboDialogUtils.createLoadingDialog(mActivity, "数据加载中...");
        } else {
            loadingDialog = WeiboDialogUtils.createLoadingDialog(mActivity, hint);
        }
    }

    /**
     * 关闭加载框
     */
    protected void closeLoading() {
        WeiboDialogUtils.closeDialog(loadingDialog);
    }

    /**
     * 退出到桌面
     */
    protected void taskToBack() {
        Intent home = new Intent(Intent.ACTION_MAIN);
//        退到桌面 并且结束当前应用
//        home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //将应用退到桌面上,保留自身
        home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
//        moveTaskToBack(true);
    }

    /**
     * 检测APP版本并更新
     */
    protected void checkAppVersion(boolean isShowLoading) {
        if (isShowLoading) {
            showLoading("检测APP版本信息...");
        }
        RetrofitManager.doGet("api/services/app/AppVersion/GetAppVersionAsync",
                new ResultCallback<CheckAppVersionBean>() {
                    @Override
                    public void onResponse(CheckAppVersionBean bean) {
                        super.onResponse(bean);
                        if (bean.isSuccess()) {
                            if (TextUtils.equals(bean.getResult().getAppVersion(), MyUtil.getVerName(mActivity))) {
                                deleteApkfile(AppConstant.apk_file_name);
//                                ToastUtil.showToast("已经是最新版!");
                                LogUtil.i(TAG, "已经是最新版!");
                            } else {
                                AlertDialog dialog = new AlertDialog.Builder(mActivity)
                                        .setIcon(R.mipmap.ic_launcher)//设置标题的图片
                                        .setTitle("发现新版本")//设置对话框的标题
                                        .setMessage("建议立即更新到最新版本！")//设置对话框的内容
                                        //设置对话框的按钮
                                        /*.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                LogUtil.e(TAG, "点击了取消");
                                                dialog.dismiss();
                                            }
                                        })*/
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                LogUtil.e(TAG, "点击了确定的按钮");
                                                dialog.dismiss();
                                                Intent service = new Intent(mActivity, UpdateService.class);
                                                startService(service);
                                            }
                                        })
                                        .setCancelable(false)
                                        .create();
                                dialog.show();
                            }
                        } else {
                            ToastUtil.showToast(bean.getError().getMessage());
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        closeLoading();
                    }
                });
    }

    /**
     * 删除安装包
     *
     * @param apkFileName
     * @return
     */
    private Boolean deleteApkfile(String apkFileName) {
        //Apk文件路径可自定义，此处用 download 文件夹
        File apkfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(), apkFileName);
        if (!apkfile.exists()) {
            LogUtil.d(TAG, "apkfile delete already! ");
        } else {
            //调用现成的文件操作方法删除文件
            if (apkfile.delete())
                LogUtil.d(TAG, "apkfile delete successfully! ");
        }
        return false;
    }

    /**
     * 清空集合
     *
     * @param list
     */
    protected void clearList(List... list) {
        for (List li : list) {
            if (li != null) {
                li.clear();
                li = null;
            }
        }
    }

    /**
     * 三方分享
     */
    protected void showShare() {
        Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.ic_launcher);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle("饭碗易购");
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl(AppConstant.Share_Url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText("饭碗易购");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        oks.setImageData(bitmap);
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl(AppConstant.Share_Url);
        // comment是我对这条分享的评论，仅在人人网使用
        oks.setComment("");
        // 启动分享GUI
        oks.show(this);
    }

    /**
     * 销毁关闭当前activity
     */
    protected void finishCurrentActivity() {
        BaseCommonApp.getBaseApp().getActivityManager().finishActivity();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 点击的是否为EditText
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            // 获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断消息通知是否可用
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void isNotificationCanUse() {
        //判断该app是否打开了通知，如果没有的话就打开手机设置页面
        if (!isNotificationEnabled()) {
            AlertDialog dialog = new AlertDialog.Builder(mActivity)
                    .setIcon(R.mipmap.ic_launcher)
                    .setTitle("消息通知")
                    .setMessage("请打开消息通知来接收我们的推送消息！")
                    .setCancelable(false)
                    //设置对话框的按钮
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            gotoSet();
                        }
                    })
                    .create();
            dialog.show();
        } else {
            //当前app允许消息通知
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private boolean isNotificationEnabled() {
        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
        AppOpsManager mAppOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = getApplicationInfo();
        String pkg = getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null;
        /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    private void gotoSet() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

    }
}
